package Arrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _697_DegreeofanArray {
    public int findShortestSubArray(int[] nums) {
        List<Integer> arsList = new ArrayList<Integer>();
        int[] ars = new int[nums.length];
        int begin = 0,end = 0;
        int maxNum = Integer.MIN_VALUE;
        int max = Integer.MIN_VALUE;
        int val =  ars[0];
        int freq = 0;
        ars = Arrays.copyOf(nums,nums.length);
        Arrays.sort(ars);
        for(int i=0;i<ars.length;i++){
            if(ars[i]==val){
                freq++;
            }else{
                if(freq>max){
                    max = freq;
                    maxNum = val;
                    val = ars[i];
                    freq = 1;
                }else{
                    val = ars[i];
                    freq = 1;
                }
            }
        }
        if(freq>max){
            maxNum = ars[ars.length-1];
            max = freq;
        }
        arsList.add(maxNum);
        val =  ars[0];
        freq = 0;
        for(int i=0;i<ars.length;i++){
            if(ars[i]==val){
                freq++;
            }else{
                if(freq==max && !arsList.contains(val)){
                    arsList.add(val);
                    val = ars[i];
                    freq = 1;
                }else{
                    val = ars[i];
                    freq = 1;
                }
            }
        }
        if(freq==max && !arsList.contains(val)){
            arsList.add(val);
        }
        int minLength = Integer.MAX_VALUE;
        System.out.println(arsList.toString());
        for(int h=0;h<arsList.size();h++){
            boolean first = true;
            int count = 0;
            for(int i=0;i<nums.length;i++){
                if(first && nums[i]==arsList.get(h)){
                    first = false;
                    begin = i;
                    count++;
                    if(count==max){
                        end = i;
                        break;
                    }
                }else if(!first && nums[i]==arsList.get(h)){
                    count++;
                    if(count==max){
                        end = i;
                        break;
                    }
                }
            }
            int min = ((end-begin)>0)?end-begin+1:1;
            if(min<minLength){
                minLength = min;
            }
        }
        return minLength;
    }
}
